// 判断用户是否登录
var username = getCookie('username')
if(!username){
    layer.msg('非法访问！',{
        icon: 2,
        time: 2000
    }, function(){
        location.href = '登录.html?callback='+location.href
    })
}else{
    // 发送请求获取当前用户信息
    $.ajax({
        url: 'http://localhost:8888/users/info?id='+getCookie('userId'),
        headers: {
            authorization: localStorage.getItem('token') || ''
        }
    }).then(res => {
        console.log(res);
        if(res.code === 1){
            var html = `
                <tr>
              <td>用户名：</td>
              <td>${res.info.username}</td>
            </tr>
            <tr>
              <td>昵称：</td>
              <td>${res.info.nickname}</td>
            </tr>
            <tr>
              <td>原密码：</td>
              <td><input type="password" name="oldpass"></td>
            </tr>
            <tr>
              <td>输入新密码</td>
              <td><input type="password" name="newpass"></td>
            </tr>
            <tr>
              <td>确认新密码：</td>
              <td><input type="password" name="repass"></td>
            </tr>
            <tr>
              <td></td>
              <td>
                <input type="button" class="zhengshuaishuai" value="提交修改">
              </td>
            </tr>
            `
            $('.rightcontent tbody').html(html)

            // ajax成功渲染页面以后，再点击提交
            submit()
        }

    })
}

// 定义提交修改的函数
function submit(){
    $('.zhengshuaishuai').click(function(){
        console.log(1);
        var oldPassword = $('[name="oldpass"]').val()
        var newPassword = $('[name="newpass"]').val()
        var rNewPassword = $('[name="repass"]').val()
        $.ajax({
            url: 'http://localhost:8888/users/rpwd',
            method: 'post',
            headers: {
                authorization: localStorage.getItem('token') || ''
            },
            data: {
                id: getCookie('userId'),
                oldPassword,
                newPassword,
                rNewPassword,
            }
        }).then(res => {
            console.log(res);
            if(res.code === 1){
                layer.msg(res.message, {
                    icon: 1,
                    time: 1500
                }, function(){
                    location.href = 'userinfo.html'
                })
            }
        })
    })
}